package com.gitee.huanminabc.fastboot.timerwheel.stage;

import com.gitee.huanminabc.jcommon.reflect.MethodUtil;
import com.gitee.huanminabc.jcommon.str.StringUtil;
import com.gitee.huanminabc.fastboot.context.AppContextUtil;
import com.gitee.huanminabc.fastboot.load.stage.poststage.AppLoadPostStage;
import com.gitee.huanminabc.fastboot.timerwheel.TimerWheelContext;
import com.gitee.huanminabc.jtimerwheel.annotation.TimerResolver;
import com.gitee.huanminabc.jtimerwheel.annotation.TimerWheel;
import com.gitee.huanminabc.jtimerwheel.base.TimerWheelException;
import com.gitee.huanminabc.jtimerwheel.core.TimerWheelManager;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 简要描述
 *
 * @Author: huanmin
 * @Date: 2025/4/3 00:11
 * @Version: 1.0
 * @Description: 文件作用详细描述....
 */
@Slf4j
public class TimeWheelLoadStage implements AppLoadPostStage {
    @Override
    public void run() {
        for (Class<?>  value : TimerWheelContext.allTimerWheelClasses) {
            TimerWheel timerWheel = value.getAnnotation(TimerWheel.class);
            //判断是否是HandlerInterceptor的实现类
            if (timerWheel != null) {
                Method[] methods = MethodUtil.getAnnotationMethod(value, TimerResolver.class);
                if (methods == null) {
                    throw new TimerWheelException(value.getName()+"类中没有找到TimerResolver注解");
                }
                for (Method method : methods) {
                    TimerResolver timerResolver = method.getAnnotation(TimerResolver.class);
                    String key = value.getName() + "." + method.getName();
                    String resolver = timerResolver.value();
                    if (StringUtil.isEmpty(resolver)) {
                        throw new TimerWheelException(key+"定时器解析器不能为空");
                    }
                    TimerWheelManager.addTimerSask(resolver, key, () -> {
                        try {
                            Object bean = AppContextUtil.getBean(value);
                            method.invoke(bean);//执行方法
                        } catch (IllegalAccessException | InvocationTargetException e) {
                            log.error("{} 定时器执行异常:", key, e);
                        }
                    });
                }
            }
        }
        TimerWheelContext.allTimerWheelClasses.clear();
        log.debug("TimeWheelLoadStage load success");
    }

}
